package com.xrtn.controller;

import com.xrtn.utils.HttpUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends HandlerInterceptorAdapter {
	/** 日志记录 */
	private Logger logger = Logger.getLogger(LoginFilter.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean handlerOk = super.preHandle(request, response, handler);

		String path = request.getContextPath();

		logger.info("handlerOk=" + handlerOk + path);
        response.addHeader("Access-Control-Allow-Origin", "*");

        if(handlerOk){
            String url = request.getRequestURI();
            logger.info("请求url:"+url);

            //拦截servlet 登录 首页不拦截
            if(     url.indexOf("/sign")!=-1
                    || url.indexOf("/css/")!=-1
                    || url.indexOf("/images/")!=-1
                    || url.indexOf("/html/")!=-1
                    || url.indexOf("/js/")!=-1
                    || url.indexOf("/fonts/")!=-1
                    || url.indexOf("/include/")!=-1
                    || url.indexOf("/assets/")!=-1
                    || url.indexOf("/swagger")!=-1
                    || url.indexOf("/couponShare")!=-1
                    || url.indexOf("/selectSysDiscountInfo")!=-1
                    || url.indexOf("/selectSubclinicList")!=-1
                    || url.indexOf("/useCoupon")!=-1
                    || url.indexOf("/gotoLogin")!=-1
                    || url.indexOf("/imgUploadCtl")!=-1
                    || url.indexOf("/uploadAliOSS")!=-1
                    || url.indexOf("/api-docs")!=-1
                    || url.indexOf("/resources")!=-1
                    || url.indexOf("/selectDoctorUpwardJob")!=-1
                    || url.indexOf("/selectDoctorMonthSaleJob")!=-1
                    || url.indexOf("/imageBrower/") != -1
                    ){
//                System.out.println("允许访问");
            } else {
//                System.out.println("登录拦截");
                //查询session,为空 跳转到登录页面
                Object userObj = request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);
                if (userObj == null) {
                    response.sendRedirect(request.getContextPath() + "/gotoLogin");
                    logger.info("未登录系统访问:拦截请求"+url);
                    return false;
                }
            }
        }

		return true;
	}
}
